﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using UCNKompetenceBors.Database;
using UCNKompetenceBors.Model;

namespace UCNKompetenceBors.Admin
{
    public partial class adminExchangeSale : System.Web.UI.Page
    {
        private PagedDataSource _pagedDataSource = new PagedDataSource();

        private int _itemsPerPage = 5;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindSubMenu();
                BindGridview(_itemsPerPage);
                
                if (Request.QueryString["i"] != null)
                {
                    ddlResultsPerPage.SelectedValue = Request.QueryString["i"].ToString();
                }

                CreatePagination();

                #region Globalization
                string culture = String.Empty;

                if (HttpContext.Current.Session["MyCulture"] != null)
                    culture = HttpContext.Current.Session["MyCulture"].ToString();

                if (!String.IsNullOrEmpty(culture))
                    GeneralTools.SetCulture(culture);

                LocalizeControls();
                #endregion
            }
        }

        /// <summary>
        /// Binds the sub menu links.
        /// </summary>
        private void BindSubMenu()
        {
            hyLinkAdminDashboard.NavigateUrl = "~/Admin/admin.aspx";
            hyLinkUserHandling.NavigateUrl = "~/Admin/adminUsers.aspx";
            hyLinkNewsHandling.NavigateUrl = "~/Admin/adminNews.aspx";
            hyLinkAdminExchange.NavigateUrl = "~/Admin/adminExchange.aspx";
            hyLinkAdminSale.NavigateUrl = "~/Admin/adminExchangeSale.aspx";
            hyLinkAdminPurchase.NavigateUrl = "~/Admin/adminExchangePurchase.aspx";
            hyLinkAdminCategory.NavigateUrl = "~/Admin/adminExchangeCategory.aspx";
            hyLinkEditInformation.NavigateUrl = "~/Admin/adminInformation.aspx";
            hyLinkContactPerson.NavigateUrl = "~/Admin/adminContactPerson.aspx";
            hylinkDepartment.NavigateUrl = "~/Admin/adminDepartment.aspx";
            hyLinkResetUsers.NavigateUrl = "~/Admin/adminUsersReset.aspx";
        }

        /// <summary>
        /// Binds the gridview with sales.
        /// </summary>
        /// <param name="itemsPerPage">Specifies the amount of sales to be shown per page.</param>
        private void BindGridview(int itemsPerPage)
        {
            _pagedDataSource.DataSource = dbAdmin.GetAllSales(0);
            _pagedDataSource.AllowPaging = true;
            _pagedDataSource.PageSize = itemsPerPage;
            if (Request.QueryString["p"] != null)
            {
                _pagedDataSource.CurrentPageIndex = Convert.ToInt32(Request.QueryString["p"]) - 1;
            }
            else
            {
                _pagedDataSource.CurrentPageIndex = 0;
            }

            ViewState["TotalPages"] = _pagedDataSource.PageCount;

            gvAdminSale.DataSource = _pagedDataSource;
            gvAdminSale.DataBind();
            
            
        }

        /// <summary>
        /// Gets the QueryString.
        /// </summary>
        /// <returns>Returns a string containing the QueryString.</returns>
        public string GetQueryString()
        {
            NameValueCollection nvc = new NameValueCollection();
            
            nvc.Add("i", ddlResultsPerPage.SelectedValue.ToString());

            if (Request.QueryString["p"] != null)
            {
                nvc.Add("p", Request.QueryString["p"].ToString());
            }
            else
            {
                nvc.Add("p", "1");
            }

            return GeneralTools.GenerateQueryString(nvc);
        }

        /// <summary>
        /// Creates the pagination.
        /// </summary>
        private void CreatePagination()
        {
            if (Request.QueryString["p"] != null)
            {
                List<WebControl> links = GeneralTools.CreatePagination(5, Convert.ToInt32(ViewState["TotalPages"]), Convert.ToInt32(Request.QueryString["p"]), Request.Url.Query, Request.Path);
                List<WebControl> links2 = GeneralTools.CreatePagination(5, Convert.ToInt32(ViewState["TotalPages"]), Convert.ToInt32(Request.QueryString["p"]), Request.Url.Query, Request.Path);

                for (int i = 0; i < links.Count; i++)
                {
                    if (links[i] is HyperLink)
                    {
                        HyperLink link = (HyperLink)links[i];
                        HyperLink link2 = (HyperLink)links2[i];

                        panTopPagination.Controls.Add(link);
                        panPagination.Controls.Add(link2);
                    }

                    else if (links[i] is Label)
                    {
                        Label label = (Label)links[i];
                        Label label2 = (Label)links2[i];

                        panTopPagination.Controls.Add(label);
                        panPagination.Controls.Add(label2);
                    } 
                }
            }
            else
            {
                List<WebControl> links = GeneralTools.CreatePagination(5, Convert.ToInt32(ViewState["TotalPages"]), 1, Request.Url.Query, Request.Path);

                List<WebControl> links2 = GeneralTools.CreatePagination(5, Convert.ToInt32(ViewState["TotalPages"]), 1, Request.Url.Query, Request.Path);

                for (int i = 0; i < links.Count; i++)
                {
                    if (links[i] is HyperLink)
                    {
                        HyperLink link = (HyperLink)links[i];
                        HyperLink link2 = (HyperLink)links2[i];

                        panTopPagination.Controls.Add(link);
                        panPagination.Controls.Add(link2);
                    }

                    else if (links[i] is Label)
                    {
                        Label label = (Label)links[i];
                        Label label2 = (Label)links2[i];

                        panTopPagination.Controls.Add(label);
                        panPagination.Controls.Add(label2);
                    } 
                }
            }
        }

        //Event fired when the selected index of the result per page dropdown list has changed
        protected void ddlResultsPerPage_SelectedIndexChanged(object sender, EventArgs e)
        {
            string url = Request.Path + GetQueryString();

            Response.Redirect(url);
        }

        /// <summary>
        /// Deletes a sale, based on the saleId parameter.
        /// </summary>
        /// <param name="saleId">Specifies the ID of the sale to be deleted.</param>
        private void DeleteRow(int saleId)
        {
            dbAdmin.DeleteSale(saleId);
        }

        //Event fired when the delete button in the gridview is clicked
        protected void gvAdminSale_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int saleID = 0;

            foreach (Label lbl in gvAdminSale.Rows[e.RowIndex].Cells[5].Controls.OfType<Label>())
            {
                if (lbl.ID == "lblSaleID")
                    saleID = Convert.ToInt32(lbl.Text);
            }

            if (saleID != 0)
                DeleteRow(saleID);

            BindGridview(_itemsPerPage);
            CreatePagination();
        }

        //Event fired when the gridview is databound
        protected void gvAdminSale_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                foreach (Label lbl in e.Row.Cells[3].Controls.OfType<Label>())
                {
                    lbl.Text = (Boolean.Parse(lbl.Text)) ? GetLocalResourceObject("StatusActive").ToString() : GetLocalResourceObject("StatusInActive").ToString();
                }

                string title = ((HyperLink)e.Row.Cells[0].Controls[0]).Text;

                foreach (LinkButton button in e.Row.Cells[4].Controls.OfType<LinkButton>())
                {
                    if (button.CommandName == "Delete")
                    {
                        button.Text = GetLocalResourceObject("btnDeleteText").ToString();
                        button.Attributes["onclick"] = "if(!confirm('Er du sikker på at du vil slette \"" + title + "\"?')) { return false; };";
                    }
                }

                foreach (Label lbl in e.Row.Cells[1].Controls.OfType<Label>())
                {
                    string culture = String.Empty;

                    if (HttpContext.Current.Session["MyCulture"] != null)
                        culture = HttpContext.Current.Session["MyCulture"].ToString();

                    Sale sale = (Sale)e.Row.DataItem;

                    if (culture.Equals("en-GB"))
                        lbl.Text = sale.Category.LocalizedCategoryName;
                    else
                        lbl.Text = sale.Category.CategoryName;
                }
            }
        }

        /// <summary>
        /// Localizes the controls of the site, based on the current UI Culture.
        /// </summary>
        private void LocalizeControls()
        {
            hyLinkAdminDashboard.Text = GetLocalResourceObject("hyLinkAdminDashboardText").ToString();
            hyLinkUserHandling.Text = GetLocalResourceObject("hyLinkUserHandlingText").ToString();
            hyLinkAdminExchange.Text = GetLocalResourceObject("hyLinkAdminExchangeText").ToString();
            hyLinkNewsHandling.Text = GetLocalResourceObject("hyLinkNewsHandlingText").ToString();
            hyLinkEditInformation.Text = GetLocalResourceObject("hyLinkEditInformationText").ToString();
            hyLinkResetUsers.Text = GetLocalResourceObject("hyLinkResetUsersText").ToString();
            hyLinkContactPerson.Text = GetLocalResourceObject("hyLinkContactPersonText").ToString();
            hylinkDepartment.Text = GetLocalResourceObject("hylinkDepartmentText").ToString();

            hyLinkAdminPurchase.Text = GetLocalResourceObject("hyLinkAdminPurchaseText").ToString();
            hyLinkAdminSale.Text = GetLocalResourceObject("hyLinkAdminSaleText").ToString();
            hyLinkAdminCategory.Text = GetLocalResourceObject("hyLinkAdminCategoryText").ToString();

            lblResultsPerPage.Text = GetLocalResourceObject("lblResultsPerPageText").ToString();
            lblSaleHeader.Text = GetLocalResourceObject("lblSaleHeaderText").ToString();

            gvAdminSale.Columns[0].HeaderText = GetLocalResourceObject("gvAdminSaleTitleText").ToString();
            gvAdminSale.Columns[1].HeaderText = GetLocalResourceObject("gvAdminSaleCategoryText").ToString();
            gvAdminSale.Columns[2].HeaderText = GetLocalResourceObject("gvAdminSaleCreateDateText").ToString();
            gvAdminSale.Columns[3].HeaderText = GetLocalResourceObject("gvAdminSaleStatusText").ToString();

            gvAdminSale.DataBind();
        }
    }
}